/*
 * @lc app=leetcode.cn id=783 lang=javascript
 *
 * [783] 二叉搜索树节点最小距离
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDiffInBST = function (root) {
  let result = Number.POSITIVE_INFINITY;
  let curr = root;
  let pre = void 0;
  const stack = [];
  // 迭代中序遍历
  while (stack.length || curr) {
    while (curr !== null) {
      stack.push(curr);
      curr = curr.left;
    }
    curr = stack.pop();
    if (pre === void 0) {
      pre = curr.val;
    } else {
      result = Math.min(result, curr.val - pre);
      pre = curr.val;
    }
    curr = curr.right;
  }

  return result;
};
// @lc code=end
